package com.chao.common.util;

import com.alibaba.fastjson.JSONObject;
import com.chao.common.util.ExpiryMap;
import com.chao.common.util.SysHttpUtil;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;

/**
 * 微信服务号对接
 */
public class WeiXin {


    public static String appID = "wxb48c8eee0b5182bd";

    public static String appSecret = "67067214d617173c228068c80fb1f11b";

    private static final String openIdUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APP_ID&secret=APP_SECRET&js_code=JSCODE&grant_type=authorization_code";

    private static final String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APP_ID&secret=APP_SECRET";

    private static final String userUrl = "https://api.weixin.qq.com/wxa/getpaidunionid?access_token=ACCESS_TOKEN&openid=OPENID";

    /**
     * token
     */
    public static com.chao.common.util.ExpiryMap<String, String> tokenMap = new ExpiryMap<>();

    private static final Logger log = LoggerFactory.getLogger(WeiXin.class);

//    public static void main(String[] args) {
//        System.out.println(getUser("071M5l0W3iSQBW20C72w3WdiuW4M5l0y"));
//    }


    public static String getUser(String code) {
        String str = com.chao.common.util.SysHttpUtil.doGet(openIdUrl.replace("APP_ID",appID).replace("APP_SECRET",appSecret).replace("JSCODE",code),new HashMap<>(),new HashMap<>());
        log.debug("微信用户{}登录{}",code,str);
        JSONObject json = JSONObject.parseObject(str);
        if(json.containsKey("openid")){
            return json.getString("openid");
//            String str1 = SysHttpUtil.doGet(userUrl.replace("ACCESS_TOKEN",getToken()).replace("OPENID",json.getString("openid")),new HashMap<>(),new HashMap<>());
//            log.debug("微信用户{}拉取数据:{}",code,str1);
//            return JSONObject.parseObject(str1);
        }
        return null;
    }

    public static JSONObject getUserInfo(String code) {
        String str = SysHttpUtil.doGet(openIdUrl.replace("APP_ID",appID).replace("APP_SECRET",appSecret).replace("JSCODE",code),new HashMap<>(),new HashMap<>());
        log.debug("微信用户{}登录{}",code,str);
        return JSONObject.parseObject(str);
    }

//    public static String getToken() {
//        if(tokenMap.containsKey("token")){
//            return tokenMap.get("token");
//        }
//        String str = SysHttpUtil.doGet(tokenUrl.replace("APP_ID",appID).replace("APP_SECRET",appSecret),new HashMap<>(),new HashMap<>());
//        JSONObject json = JSONObject.parseObject(str);
//        if(!json.containsKey("access_token")){
//            log.error("拉取token失败{}",str);
//            return "token";
//        }
//        tokenMap.put("token",json.getString("access_token"),7000000);
//        return tokenMap.get("token");
//    }

    public static JSONObject getUserMobile(String encryptedData, String sessionKey, String iv) {
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters); // 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, StandardCharsets.UTF_8);
                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}